#include "qdatatable.h"

QDataTable::QDataTable(){}

bool QDataTable::isEmpty(){
    if(this->columns.count() == 0){
        return true;
    }
    if(this->rows.count() == 0){
        return true;
    }
    return false;
}

bool QDataTable::hasColumn(QString column){
    if(column.isEmpty()){
        return false;
    }
    return this->columns.contains(column);
}

QVariantMap QDataTable::first(){
    if(this->rows.count() == 0){
        return QVariantMap();
    }
    return this->rows.first();
}

QVariantMap QDataTable::at(int idx){
    if(idx < 0){
        return QVariantMap();
    }
    if(idx > this->rows.count()){
        return QVariantMap();
    }
    if(this->rows.count() == 0){
        return QVariantMap();
    }
    return this->rows.at(idx);
}

QVariant QDataTable::at(int row,QString column){
    if(row <= 0){
        return QVariant();
    }
    if(row >= this->count()){
        return QVariant();
    }
    if(column.isEmpty()){
        return QVariant();
    }
    if(!this->columns.contains(column)){
        return QVariant();
    }
    auto json = this->rows.at(row);
    if(!json.contains(column)){
        return QVariant();
    }    
    return json.value(column);
}

QVariant QDataTable::at(int row,int column){
    if(column <= 0){
        return QVariant();
    }
    if(column >= this->columns.count()){
        return QVariant();
    }
    auto name = this->columns.at(column);
    return this->at(row,name);
}

QVariantMap QDataTable::last(){
    if(this->rows.count() == 0){
        return QVariantMap();
    }
    return this->rows.last();
}

QVariant QDataTable::scalar(){
    auto first = this->first();
    if(first.isEmpty()){
        return QVariant();
    }
    auto keys = first.keys();
    if(keys.count() == 0){
        return QVariant();
    }
    return first.value(keys.at(0));
}

int QDataTable::count(){
    return this->rows.count();
}
